package pubconfig

/*
 * @Author: huangchangqing
 * @Description: In User Settings Edit
 */
import (
	"github.com/BurntSushi/toml"
	"local.public/innerpkg/logger"
	"path/filepath"
	"reflect"
	"sync"
)

// 配置文件对应的结构体
type PublicTomlConfig struct {
	Storage struct {
		TablePrefix    string `toml:"table_prefix"`
		BusinessDbpath string `toml:"dbpath_business"`
		WoDbpath string `toml:"dbpath_wo"`
		LogsDbpath     string `toml:"dbpath_logs"`
	}

	WebServer struct {
		WebsiteDomain string `toml:"https_domain"`
	} `toml:"webserver"`

	Redis struct {
		Addr string `toml:"addr"`
		DB   int    `toml:"db"`
	} `toml:"redis"`

	MongoDb struct {
		Dsn string `toml:"dsn"`
	} `toml:"mongodb"`

	Nats struct {
		Addr string `toml:"addr"`
	} `toml:"nats"`

	Mqtt struct {
		Addr string `toml:"addr"`
	} `toml:"mqtt"`

	StaticFile struct {
		FormalRootUrlPath string `toml:"root_url_path"`
		FormalRootDirPath string `toml:"root_dir_path"`
		TmpRootUrlPath    string `toml:"tmp_root_url_path"`
		TmpRootDirPath    string `toml:"tmp_root_dir_path"`
	} `toml:"static_file"`

	Jwt struct {
		Key     string `toml:"key"`
		Timeout int    `toml:"timeout"`
	} `toml:"jwt"`

	KeyAuth struct {
		KeyName  string `toml:"keyname"`
		KeyValue string `toml:"keyvalue"`
	} `toml:"keyauth"`
}

var configPublic PublicTomlConfig
var oncePublic sync.Once

func printPubConfigSectionDetail(stu interface{}) {
	var typeInfo = reflect.TypeOf(stu)
	var valInfo = reflect.ValueOf(stu)
	num := typeInfo.NumField()
	for i := 0; i < num; i++ {
		logger.Debug(typeInfo.Field(i).Name, "=", valInfo.Field(i))
	}
}

func GetConfig() *PublicTomlConfig {
	oncePublic.Do(func() { //配置文件只读取一次
		cfgFilePath, err := filepath.Abs("./pubconf/public.toml")
		if err != nil {
			logger.Debug("未获取到pubconf/public.toml的绝对路径", err)
			return
		}
		//utils.Debug("parse toml file. filePath: %s\n", cfgFilePath)
		if _, err := toml.DecodeFile(cfgFilePath, &configPublic); err != nil {
			logger.Debug("toml文件解码失败", err)
			return
		}
		//if gin.DebugMode == "debug" {
		//	printPubConfigSectionDetail(configPublic.Storage)
		//}
	})
	return &configPublic
}
